import {$configuration, $dialog, $notice, $search, Dropdown, DropdownOption, DropdownSeparator, i18n, Icon, iSearchDataMeta, iTableInnerOperationConfig, PageThemeUtils, Plc, PlcDate, PlcOperation, PlcOv, Tag, ThemeColorSelector, ThemeDarkSelector, ThemeLocaleSelector, ThemeShapeSelector, ThemeSizeSelector, Tooltip} from "plain-design";
import {designComponent, getComponentCls, reactive} from "@peryl/react-compose";
import './AppHeader.scss';
import {useTableOption} from "../modules/plain-design/useTableOption";
import {microApp} from "../microApp";
import AppHeaderLocale from "./AppHeader.locale";
import {AppNavigator} from "./AppNavigator";
import {buildAssetsPath} from "../common/buildAssetsPath";
import {iAppMenuGroup, iAppMenuItem, MenuGroups, MenuUtils} from "../menus";

i18n.setLangs(AppHeaderLocale);

export const AppHeader = designComponent({
  name: 'app-header',
  setup() {

    const user = buildAssetsPath('images/user.png');

    const state = reactive({
      showUserDropdown: false,
    });

    const openExportTaskList = (() => {
      const innerOperationConfigs: iTableInnerOperationConfig[] = [
        { label: i18n.$intl('page.appHeader.download').d('下载'), position: 'inner', handler: ({ row }) => {$notice.warn(i18n.$intl('page.appHeader.notComplete').d('未完成！'));} },
      ];
      const mockData = [
        { name: i18n.$intl('page.appHeader.dealerList').d('经销商列表'), status: 'proceed', startTime: '2024-01-24 17:14:33', endTime: '2024-01-24 17:18:11' },
        { name: i18n.$intl('page.appHeader.orderList').d('订货列表'), status: 'proceed', startTime: '2024-01-24 17:15:00', endTime: '2024-01-24 20:18:11' },
        { name: i18n.$intl('page.appHeader.returnsList').d('退货列表'), status: 'done', startTime: '2023-12-25 13:22:20', endTime: '2023-12-25 14:22:20' },
        { name: i18n.$intl('page.appHeader.dealerList').d('经销商列表'), status: 'proceed', startTime: '2024-01-24 17:14:33', endTime: '2024-01-24 17:18:11' },
        { name: i18n.$intl('page.appHeader.orderList').d('订货列表'), status: 'proceed', startTime: '2024-01-24 17:15:00', endTime: '2024-01-24 20:18:11' },
        { name: i18n.$intl('page.appHeader.returnsList').d('退货列表'), status: 'done', startTime: '2023-12-25 13:22:20', endTime: '2023-12-25 14:22:20' },
        { name: i18n.$intl('page.appHeader.dealerList').d('经销商列表'), status: 'proceed', startTime: '2024-01-24 17:14:33', endTime: '2024-01-24 17:18:11' },
        { name: i18n.$intl('page.appHeader.orderList').d('订货列表'), status: 'proceed', startTime: '2024-01-24 17:15:00', endTime: '2024-01-24 20:18:11' },
        { name: i18n.$intl('page.appHeader.returnsList').d('退货列表'), status: 'done', startTime: '2023-12-25 13:22:20', endTime: '2023-12-25 14:22:20' },
        { name: i18n.$intl('page.appHeader.dealerList').d('经销商列表'), status: 'proceed', startTime: '2024-01-24 17:14:33', endTime: '2024-01-24 17:18:11' },
        { name: i18n.$intl('page.appHeader.orderList').d('订货列表'), status: 'proceed', startTime: '2024-01-24 17:15:00', endTime: '2024-01-24 20:18:11' },
        { name: i18n.$intl('page.appHeader.returnsList').d('退货列表'), status: 'done', startTime: '2023-12-25 13:22:20', endTime: '2023-12-25 14:22:20' },
        { name: i18n.$intl('page.appHeader.dealerList').d('经销商列表'), status: 'proceed', startTime: '2024-01-24 17:14:33', endTime: '2024-01-24 17:18:11' },
        { name: i18n.$intl('page.appHeader.orderList').d('订货列表'), status: 'proceed', startTime: '2024-01-24 17:15:00', endTime: '2024-01-24 20:18:11' },
        { name: i18n.$intl('page.appHeader.returnsList').d('退货列表'), status: 'done', startTime: '2023-12-25 13:22:20', endTime: '2023-12-25 14:22:20' },
      ];
      const notificationOption = useTableOption({
        showRows: 10,
        paginationAttrs: {
          pageSize: mockData.length,
        },
        url: {
          base: '',
          query: {
            async request() {
              if (!!notificationOption.state.list.length) {
                $notice.warn('当前为测试数据！');
              }
              return {
                success: true,
                code: '200',
                list: mockData,
                hasNext: false,
              };
            },
          }
        },
        title: i18n.$intl('page.appHeader.exportTask').d('导出任务'),
        render() {
          return <>
            <Plc title={i18n.$intl('page.appHeader.taskName').d("任务名称")} field="name" overflowTooltip width={100}/>
            <PlcOv title={i18n.$intl('page.appHeader.taskStatus').d("状态")} field="status" ov="TASK_STATUS" width={80} v-slots={{
              normal: ({ row }) => {
                if (row.status === 'proceed') {
                  return <Tag label={i18n.$intl('page.appHeader.processing').d("进行中")} color="primary" style={{ transform: 'scale(0.8)', color: 'var(--pl-pbfc)' }}/>;
                } else if (row.status === 'done') {
                  return <Tag label={i18n.$intl('page.appHeader.complete').d("已完成")} color="success" style={{ transform: 'scale(0.8)', }}/>;
                } else if (row.status === 'error') {
                  return <Tag label={i18n.$intl('page.appHeader.fail').d("执行失败")} color="error" style={{ transform: 'scale(0.8)', }}/>;
                }
              }
            }}/>
            <PlcDate title={i18n.$intl('page.appHeader.startTime').d("开始时间")} field="startTime" width={165}/>
            <PlcDate title={i18n.$intl('page.appHeader.endTime').d("结束时间")} field="endTime" width={165}/>
            <PlcOperation operations={innerOperationConfigs}/>
          </>;
        },
      });
      const $object = $configuration.get('object')!;
      return () => {
        $object({ option: notificationOption, readonly: true, dialogProps: { width: '900px', noFoot: true } });
      };
    })();

    const openMessageList = (() => {

      const imgs = {
        assistant: <div className="pro-manager-bell-msg-img" style={{ backgroundColor: '#fe5d59' }}><Icon icon={'pi-message'}/></div>,
        opportunity: <div className="pro-manager-bell-msg-img" style={{ backgroundColor: '#ffce3e' }}><Icon icon={'pi-bulb'}/></div>,
        advertise: <div className="pro-manager-bell-msg-img" style={{ backgroundColor: '#b7dedd' }}><Icon icon={'pi-book'}/></div>,
        ticket: <div className="pro-manager-bell-msg-img" style={{ backgroundColor: '#3191e5' }}><Icon icon={'pi-gift'}/></div>,
        shop: <div className="pro-manager-bell-msg-img" style={{ backgroundColor: '#fe5d59' }}><Icon icon={'pi-home'}/></div>,
      };

      let msgData = [
        {
          title: '职言小助手·官方',
          message: '同事圈内容更新提醒',
          time: '2021-05-07',
          img: imgs.assistant,
        },
        {
          title: '机遇小助手·官方',
          message: 'hi~, 有15家公司正在挖掘目标人才，这些职位很适合您。',
          time: '2021-04-25',
          img: imgs.opportunity,
        },
        {
          title: '英孚教育·广告',
          message: '英语有多好，职场就有多强大！',
          time: '2021-04-21',
          img: imgs.advertise,
        },
        {
          title: '红包助手·官方',
          message: '送您一个可提现红包。',
          time: '2021-03-19',
          img: imgs.ticket,
        },
        {
          title: '机会来啦',
          message: '这里有您最匹配的机会，最前瞻的报告',
          time: '2021-02-22',
          img: imgs.shop,
        },
      ];
      msgData = [...msgData, ...msgData, ...msgData];

      const render = () => (
        msgData.map((item, index) => (
          <div className="pro-manager-bell-item" key={index}>
            {item.img}
            <div className="pro-manager-bell-item-info">
              <div>
                <span>{item.title}</span>
                <span>{item.time}</span>
              </div>
              <div>{item.message}</div>
            </div>
          </div>
        ))
      );

      return () => (
        $dialog({
          title: i18n.$intl('page.appHeader.message').d('通知消息'),
          position: 'right',
          noContentPadding: true,
          render,
        })
      );
    })();

    const resetTheme = () => {
      PageThemeUtils.toggle(false);
      PageThemeUtils.primary(null);
      PageThemeUtils.size(null);
      PageThemeUtils.shape(null);

      window.location.reload();
    };

    const openSearch = () => {
      $search({
        cacheName: 'search_menu',
        getData: async (searchKey) => {
          searchKey = searchKey.toLowerCase();
          const list: iSearchDataMeta[] = [];
          const getLabel = (item: iAppMenuGroup | iAppMenuItem): string => {
            return i18n.$intl(item.name).d(item.name);
          };
          MenuGroups.data.forEach(group => {

            const matchMenus = getLabel(group).toLowerCase().indexOf(searchKey) > -1 ?
              group.menus :
              group.menus.filter(menu => getLabel(menu).toLowerCase().indexOf(searchKey) > -1);
            if (!!matchMenus.length) {
              list.push({ type: 'group', title: group.name });
              list.push(...matchMenus.map(menu => ({
                title: menu.name,
                desc: '',
                type: 'page' as const,
                data: { group, menu },
              })));
            }
          });
          return list;
        },
        onSelect: (dataMeta: any) => {
          MenuUtils.openMenu(dataMeta.data.menu, dataMeta.data.group);
        },
      });
    };

    const login = () => {
      state.showUserDropdown = false;
      microApp.login.logout();
    };

    return () => (
      <>
        <div className="app-header">
          <div className="app-header-logo-wrapper">
            <img src={buildAssetsPath('images/pro_logo.png')} alt=""/>
            <span>Micro Pro</span>
          </div>
          <div className="app-header-start">
            <AppNavigator/>
          </div>
          <div className="app-header-end">
            <ThemeColorSelector reloadOnChange/>
            <ThemeDarkSelector reloadOnChange/>
            <ThemeShapeSelector reloadOnChange/>
            <ThemeSizeSelector reloadOnChange/>
            <ThemeLocaleSelector reloadOnChange/>
            <Tooltip message={i18n.$intl('page.appHeader.search').d("搜索")}>
              <div className={getComponentCls("theme-selector")} onClick={openSearch}>
                <Icon icon="pi-search"/>
              </div>
            </Tooltip>
            <Tooltip message={i18n.$intl('page.appHeader.exportTask').d("导出任务")}>
              <div className={getComponentCls("theme-selector")} onClick={openExportTaskList}>
                <Icon icon="pi-download"/>
                <div className="app-header-button-tip"><span>3</span></div>
              </div>
            </Tooltip>
            <Tooltip message={i18n.$intl('page.appHeader.message').d("通知消息")}>
              <div className={getComponentCls("theme-selector")} onClick={openMessageList}>
                <Icon icon="pi-notification"/>
                <div className="app-header-button-tip"><span>99+</span></div>
              </div>
            </Tooltip>

            <Dropdown
              v-model={state.showUserDropdown}
              trigger="hover"
              sizeEqual
              disableCloseOnClickOption
              hideOnClickReference={false}
              v-slots={{
                default: () => (
                  <div className="app-header-user">
                    <img src={user}/>
                    <div>
                      <div className="app-header-user-name">{i18n.$intl("page.crmHome.userFullName").d('系统管理员')}</div>
                      <div className="app-header-user-postn">{i18n.$intl('page.crmHome.userPosition').d('产品技术部前端工程师 qqqq')}</div>
                    </div>
                  </div>
                ),
                popper: () => <>
                  <DropdownOption label={i18n.$intl('page.appHeader.feedback').d("新建工单")} icon="pi-customer-service" onClick={() => state.showUserDropdown = false}/>
                  <DropdownOption label={i18n.$intl('page.appHeader.switchOrganization').d("切换组织")} icon="pi-relation" onClick={() => state.showUserDropdown = false}/>
                  <DropdownOption label={i18n.$intl('page.appHeader.switchPosition').d("切换职位")} icon="pi-user-group" onClick={() => state.showUserDropdown = false}/>
                  <DropdownOption label={i18n.$intl('page.appHeader.personalCenter').d("个人中心")} icon="pi-user" onClick={() => state.showUserDropdown = false}/>
                  <DropdownOption label={i18n.$intl('page.appHeader.resetTheme').d("重置主题")} icon="pi-computer" onClick={() => {
                    resetTheme();
                  }}/>
                  {/*<DropdownOption icon={PageThemeUtils.state.dark ? 'pi-sun' : 'pi-moon'} onClick={() => handler.onDarkChange()}>
                    <div className="app-theme-switcher">
                      <span>黑暗主题</span>
                      <Toggle size="small" status="secondary" square modelValue={!!PageThemeUtils.state.dark} trueValue={true} falseValue={false}/>
                    </div>
                  </DropdownOption>*/}
                  <DropdownSeparator/>
                  <DropdownOption label={i18n.$intl('page.appHeader.logout').d("退出登录")} icon="pi-share-internal" onClick={login}/>
                </>
              }}
            />
          </div>
        </div>
        <div className="app-header-filter"/>
        <div className="app-header-filter-bg"/>
      </>
    );
  },
});
